/*
Copyright 2010 Bryce Alcock

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.com

 */

package com.ecocrypt.proxy.forwarder.remote;

import java.io.IOException;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * @author bryce.alcock
 */
public class ServiceRequestListener implements Runnable {

    int servicePort = 47906;
    AtomicInteger errorCount = new AtomicInteger();
    ArrayList<RemoteServiceRequest> currentRemoteServiceRequestList = new ArrayList<RemoteServiceRequest>();

    public ServiceRequestListener(Integer sp){
        if(sp!=null){
            servicePort=sp;
        }
    }

    public void add(Serializable s){
	for (RemoteServiceRequest remoteServiceRequest : currentRemoteServiceRequestList) {
	    remoteServiceRequest.add(s);
	}
    }

    public void run() {
        Thread t = Thread.currentThread();
        t.setName("ServiceRequestListener Port: "+servicePort);

       	ServerSocket ss;
	try {
	    ss = new ServerSocket(servicePort);
	} catch (IOException ex) {
	    ex.printStackTrace(System.out);
	    throw new RuntimeException("Can't start the Forwarder Call get next exception to see why-> " + ex.getMessage(), ex);
	}


	while (true) {
	    try {
		Socket requestSocket = ss.accept();
		//  Now we have to start 2 threads.
		//  One to read from the socket,
		//  and one to right back to the socket.

		RemoteServiceRequest rsr = new RemoteServiceRequest(requestSocket);
		currentRemoteServiceRequestList.add(rsr);
		rsr.startThreads();



	    } catch (Throwable ex) {

		System.out.println("Error Accepting a Socket for " + servicePort + ":  Total Error count->" + errorCount.incrementAndGet());
		ex.printStackTrace(System.out);
	    }
	}
    }
}
